﻿using SearchStar.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;

namespace SearchStar.Controllers
{
    public class ArticleUIController : Controller
    {
        //http client object and take the helper classes
        private string apiUrl = "";
        HttpClient client = new HttpClient();

        public ArticleUIController()
        {
        }

        public ArticleUIController(string baseUrl, string apiUrl)
        {
            this.apiUrl = apiUrl;
            this.client.BaseAddress = new Uri(baseUrl);
            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
        //
        // GET: /ArticleUI/

        public ActionResult Index()
        {
            return View();
        }

        public List<Article> Get()
        {
            HttpResponseMessage response = client.GetAsync(this.apiUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var articles = response.Content.ReadAsAsync<IEnumerable<Article>>().Result;
                return articles.ToList();
            }
            else
            {
                return null;
            }
        }

        public ActionResult GetArticles(string q)
        {
            var articles = SearchArticles(q);
            return PartialView(articles);
        }

        public List<Article> SearchArticles(string searchWord)
        {
            HttpResponseMessage response = client.GetAsync(this.apiUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var articles = response.Content.ReadAsAsync<IEnumerable<Article>>().Result;

                articles = articles.Where(a => a.Text.Contains(searchWord));

                return articles.ToList();
            }
            else
            {
                return null;
            }
        }

    }
}
